// pages/login/accredit/accredit.js
import {
  login
} from '../../../api/user.js';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    code: '',
    checked: false,
    memberId: null,
    companyId: null,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if (options.scene) {
      let scene = param2Obj(decodeURIComponent(options.scene))
      this.data.memberId = Number(scene.memberId);
    }
    this.data.companyId = options.companyId;
    // 登录
    wx.login({
      success: res => {
        this.data.code = res.code;
      }
    })
  },

  /**
   * 同意协议
   */
  handleAgree(e) {
    this.setData({
      checked: e.detail.value[0] === '1'
    })
  },

  /**
   * 授权
   */
  onGetUserInfo(e) {
    if (e.detail.errMsg !== 'getUserInfo:ok') {
      wx.showToast({
        title: '授权失败,请重新授权',
        icon: 'none'
      })
      return;
    }
    getApp().globalData.userInfo = e.detail.userInfo;
    const _oTemp = {
      code: this.data.code,
      iv: e.detail.iv,
      encryptedData: e.detail.encryptedData,
      memberId: this.data.memberId,
      companyId: this.data.companyId,
    }

    // console.log(JSON.stringify(_oTemp));
    this.wxLogin(_oTemp);
  },

  /**
   * 微信登录
   * @param obj 授权内容
   */
  wxLogin(obj) {
    login(obj).then(res => {
      getApp().globalData.isLogin = true;
      getApp().globalData.token = res.token;
      getApp().globalData.memberId = res.id;
      getApp().globalData.openid = res.openId;
      getApp().globalData.roleId = res.roleId;
      Object.assign(getApp().globalData.userInfo, res);
      wx.navigateBack({})
    }).catch(err => {
      getApp().globalData.memberId = err.data.memberId;
      if (err.code === 'A0002') { // 未绑定手机号
        wx.redirectTo({
          url: '/pages/login/mobile/bind',
        })
      } else if (err.code === 'A0003') { // 未完善信息
        wx.redirectTo({
          url: '/pages/login/information/index',
        })
      } else {
        // 重新获取 code
        wx.login({
          success: res => {
            this.data.code = res.code;
          }
        })
      }
    })
  }
})